# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/3/13 8:08 下午
# @Author : 曹庭
# @File : profile.py
# @Software: PyCharm

from . import api
from course.utils.commons import login_required
from flask import g, current_app, jsonify, request,session
from course.utils.response_code import RET
from course.utils.image_storage import storage
from course.models import User
from course import db, constants


@api.route("/users/avatar", methods=["POST"])
@login_required
def set_user_avatar():
    """
    设置用户的头像
    参数：图片  用户id(g.user_id)
    :return:
    """
    # 装饰器的代码中已经将user_id保存到g对象中，所有视图中可以直接读取
    user_id = g.user_id

    # 获取图片
    image_file = request.files.get("file")
    print("-----------------------------------")
    print(image_file)

    if image_file is None:
        return jsonify(errno=RET.PARAMERR, errmsg=["未上传图片"])

    image_data = image_file.read()

    # 调用七牛上传图片
    try:
        file_name = storage(image_data)
        print("七牛上传图片：" + file_name)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 保存文件名到数据库中
    # try:
    #     User.query.filter_by(id=user_id).update({"avatar_url": file_name})
    #     db.session.commit()
    # except Exception as e:
    #     db.session.rollback()
    #     current_app.logger.error(e)
    #     return jsonify(error=RET.DBERR, errmsg="保存图片信息失败")

    avatar_url = constants.QINIU_URL_DOMAIN + file_name
    # 保存成功返回
    return jsonify(error=RET.OK, errmsg="头像保存成功", data={"avatar_url": avatar_url})


@api.route("/saveProfile", methods=["POST"])
@login_required
def save_profile():
    """
    保存个人信息 
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id

    request_dict = request.get_json()
    print(request_dict)
    avatar_url = request_dict.get("avatar_url")
    username = request_dict.get("username")
    mail = request_dict.get("mail")

    # 获取图片的名称
    avatar_url_list = avatar_url.split("/")
    avatar_url = avatar_url_list[-1]
    print(avatar_url)

    # 保存文件名到数据库中
    try:
        User.query.filter_by(id=user_id).update({"avatar_url": avatar_url, "user_name": username, "mail": mail})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="数据保存失败")

    session["avatar"] = constants.QINIU_URL_DOMAIN + avatar_url
    session["user_name"] = username
    session["mail"] = mail

    return jsonify(code=RET.OK, errmsg="保存成功")
